﻿using System;
using AutoMapper;
using Framework.Exceptions;
using Interfaces.BusinessLogic;
using Interfaces.Models;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using ServiceInfrastructure.Models.SecurityModels.Models;

namespace BusinessLogic.Services.Mapping
{
    public class UserContractMapper : IEntityMapper<IUser, User>
    {
        private static void CreateMapping()
        {
            Mapper.Reset();
            Mapper.CreateMap<IUser, User>();
            Mapper.CreateMap<IRole, Role>()
                  .ForMember(x => x.Users, opt => opt.Ignore());
        }

        public User Map(IUser entity)
        {
            User newUser = null;
            
            try
            {
                CreateMapping();

                newUser = Mapper.Map<IUser, User>(entity);
            }
            catch (Exception exception)
            {
                if (ExceptionHandlingManager.HandleException(exception, PolicyNames.DALPolicy))
                    throw;
            }

            return newUser;
        }
    }
}
